<template>
  <div v-if="swiperBannerList && swiperBannerList.length > 0">
    <!-- 左上角城市图标 -->
    <city-icon></city-icon>
    <!-- 轮播图区域 -->
    <swiper class="film-swiper" :options="swiperOption">
      <swiper-slide class="film-swiper-banner" v-for="banner in swiperBannerList" :key="banner.bannerId">
        <img :src="banner.imgUrl" :alt="banner.name" />
      </swiper-slide>
    </swiper>
  </div>
  <!-- 顶部导航栏 - 仅当无轮播图区域时出现 -->
  <van-nav-bar v-else title="电影" @click-left="$router.push('/cities')" fixed placeholder>
    <template #left>
      <div class="van-navbar-left">
        <span>{{ cityName }}</span><i class="iconfont icon-xia"></i>
      </div>
    </template>
  </van-nav-bar>
</template>

<script>
import { mapState } from 'vuex'
import { NavBar } from 'vant'
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/css/swiper.min.css'
import { load, getTimestamp } from '@/utils'
import CityIcon from '@/components/CityIcon'

export default {
  name: 'FilmSwiper',
  props: {
    cityName: String
  },
  components: { Swiper, SwiperSlide, CityIcon, [NavBar.name]: NavBar },
  data () {
    const vm = this // 初始化时保存当前vm实例对象
    return {
      swiperBannerList: [],
      // 轮播设置
      swiperOption: {
        loop: true,
        autoplay: {
          delay: 3000,
          disableOnInteraction: false
        },
        on: {
          // 轮播图初始化完成后回调
          init () {
            vm.$nextTick(() => {
              // 当只有一张图片时停止自动轮播
              if (vm.swiperBannerList.length <= 1) this.autoplay.stop()
            })
          },
          // 轮播图点击时回调
          tap () {
            try {
              const index = this.realIndex // 获取下标索引，此处的this为swiper实例对象，而不是vue实例对象
              const actionDataStr = vm.swiperBannerList[index].actionData // 根据数组下标获取对应的actionData
              const actionDataObj = JSON.parse(actionDataStr) // 字符串转对象
              vm.$router.push(`/film/${actionDataObj.businessId}`) // 跳转路由至电影详情页
            } catch (error) {
              console.warn(error)
            }
          }
        }
      }
    }
  },
  computed: {
    ...mapState('CityModule', ['cityId'])
  },
  mounted () {
    load({
      url: `/gateway?type=2&cityId=${this.cityId}&k=${getTimestamp()}`,
      headers: { 'X-Host': 'mall.cfg.common-banner' }
    })
      .then((res) => {
        this.swiperBannerList = res.data.data
      })
      .catch((err) => {
        this.swiperBannerList = []
        console.warn(err)
      })
  }
}
</script>

<style lang="scss" scoped>
.film-swiper {
  height: 210px;
  background-color: #f9f9f9;
  .film-swiper-banner {
    display: flex;
    align-items: center;
    img {
      width: 100vw;
      cursor: pointer;
    }
  }
}
</style>
